package cn.like.gateway.config;

import cn.like.base.support.result.Rest;
import cn.like.satoken.core.SatokenExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import reactor.core.publisher.Mono;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
@Slf4j
public class ExceptionConfiguration extends SatokenExceptionHandler {

    @ExceptionHandler(value = BlockException.class) // 因为这里是示例，所以暂时使用 JSONObject，实际项目最终定义一个 CommonResult。
    public Mono<Rest<?>> blockExceptionHandler(BlockException ex, HttpServletRequest request) {

        log.error("sentinel 降级 资源名称:{}", ex.getRule().getResource(), ex);

        return Mono.just(Rest.of("当前系统繁忙中，请稍后访问", HttpStatus.TOO_MANY_REQUESTS.value(), ex.getMessage())
                .path(request.getRequestURI()));
    }
}